package com.aifeng.hassan_food.sale

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.aifeng.base.BaseActivity
import com.aifeng.base.addItems
import com.aifeng.base.loadRoundedImage
import com.aifeng.base.setHtmlSmall
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.base.visible
import com.aifeng.common_ui.helper.*
import com.aifeng.common_ui.view.FullyLinearLayoutManager
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.mine.AddressActivity
import com.aifeng.model.CommonData
import com.aifeng.oss.scaleImage
import com.aifeng.utils.*
import com.aifeng.viewmodel.AdressViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import kotlinx.android.synthetic.main.activity_confirm.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel

class ConfirmActivity : BaseActivity() {

    private val mAdressList = ArrayList<CommonData>()
    private val mSelectId = MutableLiveData("")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_confirm)
        initTitle(title = "确认订单", divider = false)

        @Suppress("UNCHECKED_CAST")
        mList.addItems(intent.getSerializableExtra("data") as ArrayList<CommonData>)
        mAdapter.updateData(mList)

        getData()
    }

    override fun getViewModel() = getViewModel<AdressViewModel>()

    @SuppressLint("SetTextI18n")
    override fun initTitle(title: String, name: String, divider: Boolean) {
        super.initTitle(title, name, divider)
        confirm_list.apply {
            isNestedScrollingEnabled = false
            layoutManager = FullyLinearLayoutManager(baseContext)
            mAdapter = SlimAdapter.create()
                .register<CommonData>(R.layout.item_shop_inner_list_80) { inner, jector ->

                    val index = mList.indexOf(inner)
                    val isLast = index == mList.size - 1

                    jector.text(R.id.item_shop_name, inner.goodname)
                        .text(R.id.item_shop_type, "规格：${inner.specs}")
                        .text(
                            R.id.item_shop_price,
                            setHtmlSmall("¥ ${inner.price.formatDecimalWhenHave()}", "¥")
                        )
                        .text(R.id.item_shop_num, "x${inner.num}")
                        .with<ImageView>(R.id.item_shop_img) {
                            val imgs = inner.goodimg.split(",")
                            it.loadRoundedImage(url = imgs[0].scaleImage())
                        }
                        .visibility(
                            R.id.item_shop_set,
                            if (inner.specstype == "package") View.VISIBLE else View.GONE
                        )
                        .visibility(
                            R.id.item_shop_divider,
                            if (isLast) View.GONE else View.VISIBLE
                        )
                }
                .attachTo(this)
        }

        confirm_shop.text = getString("shopName")
        confirm_zhong.text = ""

        observe("adressConfirm") { result ->
            val items = result.split(",")
            when (items[0]) {
                "check" -> {
                    confirm_has.visible()
                    confirm_no.gone()
                    mSelectId.value = items[1]
                    confirm_name.text = items[2]
                    confirm_tel.text = items[3]
                    confirm_adress.text = items[4]
                }
                "delete" -> {
                    mAdressList.removeAll { it.id == mSelectId.value }
                    if (mAdressList.isNotEmpty()) {
                        val adressData = mAdressList[0]
                        mSelectId.value = adressData.id
                        confirm_name.text = adressData.receiver
                        confirm_tel.text = adressData.phone
                        confirm_adress.text = when {
                            adressData.pro in adressData.address
                                    || adressData.city in adressData.address
                                    || adressData.area in adressData.address -> adressData.address
                            else -> adressData.pro + adressData.city + adressData.area + adressData.address
                        }
                    } else {
                        confirm_has.gone()
                        confirm_no.visible()
                        mSelectId.value = ""
                    }
                }
                "modify" -> {
                    if (mSelectId.value == items[1]) {
                        confirm_name.text = items[2]
                        confirm_tel.text = items[3]
                        confirm_adress.text = items[4]
                    }
                }
                "add" -> {
                    if (mAdressList.isEmpty()) getData()
                }
            }
        }

        mSelectId.observe(
            getLifecycleOwner(),
            Observer { value ->
                if (value.isNotEmpty()) getExpress(value)
                else  {
                    getViewModel().calculateTotal(mList) {
                        confirm_zong.text = "¥ ${it.formatDecimal()}"
                        confirm_total.text = "¥ ${it.formatDecimal()}"
                    }
                }
            }
        )

        confirm_has.oneClick { startActivity<AddressActivity>("model" to "select") }
        confirm_no.oneClick { startActivity<AddressActivity>("model" to "select") }
        bt_submit.oneClick {
            if (mSelectId.value.isNullOrEmpty()) {
                toast("请选择收货地址！")
                return@oneClick
            }

            getViewModel().submitOrder(
                "userid" to getString("userId"),
                "goodlist" to intent.getExtra("json"),
                "receiver" to confirm_name.textString(),
                "phone" to confirm_tel.textString(),
                "addressid" to (mSelectId.value ?: ""),
                "address" to confirm_adress.textString(),
                "deliverymode" to "1",
                "remarks" to confirm_msg.trimString(),
                "reselleruserid" to getString("userId")
            )
                .bindLifeCycle(getLifecycleOwner())
                .subscribeByNoError(
                    event = getViewModel(),
                    onSuccess = {
                        val obj = JSONObject(it)
                        LiveEventBus.get("loginStatus").post("login")
                        startActivity<ConfirmPayActivity>(
                            "orderNo" to obj.optNotNull("orderon"),
                            "price" to obj.optNotNull("amount"),
                            "orderId" to obj.optNotNull("orderid"),
                            "express" to obj.optNotNull("expressfee")
                        )
                        ActivityStack.screenManager.popActivities(this::class.java)
                    }
                )
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getExpress(adressId: String) {
        getViewModel().expressFee(
            getString("userId"),
            adressId,
            intent.getExtra("json")
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByNoSuccess(
                event = getViewModel(),
                onSuccess = { json ->
                    val fee = JSONObject(json).optNotNull("data")

                    getViewModel().calculateTotal(mList) {
                        confirm_zong.text = "¥ ${it.formatDecimal()}"
                        confirm_total.text =
                            "¥ ${(it.toNotDouble() + fee.toNotDouble()).formatDecimal()}"
                    }
                }
            )
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getList(1, getString("userId"))
            .doOnSubscribe { showLoading() }
            .doFinally { dismissLoading() }
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = { items ->
                    mAdressList.clear()
                    mAdressList.addItems(items)

                    if (mAdressList.isNotEmpty()) {
                        confirm_has.visible()
                        confirm_no.gone()
                        val adressData =
                            mAdressList.firstOrNull { it.type == "1" } ?: mAdressList[0]
                        mSelectId.value = adressData.id
                        confirm_name.text = adressData.receiver
                        confirm_tel.text = adressData.phone
                        confirm_adress.text = when {
                            adressData.pro in adressData.address
                                    || adressData.city in adressData.address
                                    || adressData.area in adressData.address -> adressData.address
                            else -> adressData.pro + adressData.city + adressData.area + adressData.address
                        }
                    }
                }
            )
    }

}
